package ynu.elm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import ynu.elm.entity.User;
import ynu.elm.service.UserService;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/UserController")
@CrossOrigin(origins = "http://localhost:5173")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @GetMapping("/getUserByIdByPass")
    public ResponseEntity<?> login(
            @RequestParam String username,
            @RequestParam String password) {

        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名和密码不能为空"));
        }

        try {
            User user = userService.login(username, password);

            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("userId", user.getUserId());
                response.put("username", user.getUsername());
                response.put("createdAt", user.getCreatedAt());
                response.put("message", "登录成功");

                return ResponseEntity.ok(user);
            } else {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(createErrorResponse("用户名或密码错误"));
            }
        } catch (Exception e) {
            System.err.println("登录接口异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("服务器内部错误，请稍后重试"));
        }
    }

    /**
     * 用户注册接口
     * @param registerData 注册数据
     * @return 注册结果
     */
    @PostMapping("/saveUser")
    public ResponseEntity<?> register(@RequestBody Map<String, String> registerData) {

        String username = registerData.get("userId");
        String password = registerData.get("password");

        // 参数验证
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名和密码不能为空"));
        }

        // 用户名长度验证
        if (username.length() < 3 || username.length() > 20) {
            return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名长度必须在3-20个字符之间"));
        }

        // 密码长度验证
        if (password.length() < 6 || password.length() > 20) {
            return ResponseEntity.badRequest()
                    .body(createErrorResponse("密码长度必须在6-20个字符之间"));
        }

        try {
            int result = userService.register(username, password);

            switch (result) {
                case 1:
                    return ResponseEntity.ok(createSuccessResponse("注册成功", result));
                case 0:
                    return ResponseEntity.status(HttpStatus.CONFLICT)
                            .body(createErrorResponse("用户名已存在"));
                default:
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .body(createErrorResponse("注册失败，请稍后重试"));
            }

        } catch (Exception e) {
            System.err.println("注册接口异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("服务器内部错误，请稍后重试"));
        }
    }

    /**
     * 获取用户信息接口
     * @param username 用户名
     * @return 用户信息
     */
    @GetMapping("/getUserInfo")
    public ResponseEntity<?> getUserInfo(@RequestParam String username) {

        if (!StringUtils.hasText(username)) {
            return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户名不能为空"));
        }

        try {
            User user = userService.getUserByUsername(username);

            if (user != null) {
                Map<String, Object> response = new HashMap<>();
                response.put("userId", user.getUserId());
                response.put("username", user.getUsername());
                response.put("createdAt", user.getCreatedAt());

                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(createErrorResponse("用户不存在"));
            }

        } catch (Exception e) {
            System.err.println("获取用户信息异常: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(createErrorResponse("服务器内部错误，请稍后重试"));
        }
    }

    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message, Object data) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("data", data);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}